<?php
namespace frontend\controllers;

use common\models\Message;
use common\utils\XCache;
use common\utils\XMap;
use Yii;

/**
 * 默认控制器
 */
class SiteController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        $this->layout = XMap::layoutHome();
        return $this->xrender('index');
    }

    /**
     * 通过Ajax保存留言
     */
    public function actionMessage()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        //通过SESSION简单过虑刷新情况，这里设为30秒
        $session = Yii::$app->session;
        $preTime = $session->get('_message_save', 0);
        $time = time();
        if ($time - $preTime > 29) {//29=30-1秒
            if (Yii::$app->request->isPost && Yii::$app->request->isAjax) {
                $model = new Message();
                if ($model->load(Yii::$app->request->post()) && $model->validate()) {
                    if ($model->save()) {
                        $session->set('_message_save', $time);
                        return ['success' => true];
                    } else {
                        return ['success' => false, 'errors' => $model->errors];
                    }
                } else {
                    $error = "";
                    if (array_key_exists('content', $model->errors)) {
                        $error = $model->firstErrors['content'];
                    } elseif (array_key_exists('email', $model->errors)) {
                        $error = $model->firstErrors['email'];
                    }
                    return ['success' => false, 'errors' => $error];
                }
            }
        } else {
            return ['success' => false, 'errors' => "您提交的时间频率太快了，请一会再尝试"];
        }
    }

}
